package cn.itcast.exceptionHandler;

import cn.itcast.common.R;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(MySQLIntegrityConstraintViolationException.class)
    public R<String> handleDuplicateUsername(MySQLIntegrityConstraintViolationException exception){
        log.info(exception.getMessage());
        if (exception.getMessage().contains("Duplicate entry")){
            String[] mes = exception.getMessage().split(" ");
            log.error("用户名:{}已存在",mes[2]);
            return R.error("用户名"+mes[2]+"已存在，添加失败");
        }
       return R.error("未知异常");

    }
    @ExceptionHandler(CustomException.class)
    public R<String> handleDeleteException(CustomException customException){
        log.warn(customException.getMessage());
        return R.error(customException.getMessage());
    }
}
